package sg.java.concepts.performance.string;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DurationFormatUtils;

/**
 * Shows the performance difference between using Apache Common Lang StringUtils
 * VS Java's own implementation or replace and replaceAll.
 * 
 * @author Oh Chin Boon
 * 
 */
public class StringReplaceApp {
	public static String replaceUsingStringReplaceAll(String subject) {
		return subject.replaceAll("\\r|\\n", "");
	}

	public static String replaceUsingApacheLang(String subject) {
		return StringUtils.replace(StringUtils.replace(subject, "\r", ""),
				"\n", "");
	}

	/**
	 * Note that {@link String#replace(charSequence, charSequence)} is a feature
	 * of Java 1.5 abd above.
	 * 
	 * <p>
	 * If you are using Java 1.4.2 and below, you may only have the option of
	 * the same method that takes in <code>char</code>.
	 * 
	 * @param subject
	 * @return
	 */
	public static String replaceUsingStringReplace(String subject) {
		return subject.replace("\r", "").replace("\n", "");
	}

	public static void main(String args[]) {
		final int iteration = 300 * 1000 * 1000;
		
		long time = System.currentTimeMillis();

		for (int i = 0; i < iteration; i++) {
			replaceUsingApacheLang(i + "\n");
		}

		long completedIn = System.currentTimeMillis() - time;

		System.out.println("Apache finished running in: "
				+ DurationFormatUtils
						.formatDuration(completedIn, "HH:mm:ss:SS"));

		time = System.currentTimeMillis();

		for (int i = 0; i < iteration; i++) {
			replaceUsingStringReplace(i + "\n");
		}

		completedIn = System.currentTimeMillis() - time;

		System.out.println("JAVA built-in replace finished running in: "
				+ DurationFormatUtils
						.formatDuration(completedIn, "HH:mm:ss:SS"));

		time = System.currentTimeMillis();

		for (int i = 0; i < iteration; i++) {
			replaceUsingStringReplaceAll(i + "\n");
		}

		completedIn = System.currentTimeMillis() - time;

		System.out.println("JAVA built-in replaceAll finished running in: "
				+ DurationFormatUtils
						.formatDuration(completedIn, "HH:mm:ss:SS"));
	}
}
